import {
  list
} from '../../api/ingredients'
import {
  numSettingsType 
} from '../../dataSource'
import recipe from '../../api/recipe'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    list: [],
    dropList: [],
    selectList: [],
    show: false,
    alias: {},
    values: [],
    ingredientsList: [],
    id: '',
    name: '',
    root: getApp().globalData.root,
    total: 0,
    refreshLoading: false,
    numSettingsType,
    enabledScroll: true,
    _performanceData: {
      x: null,
      y: null,
      z: null,
      tRongCorrectionValue: null
    },
    isGlaze: true //是否是采集过程中创建釉料
  },

  addPF(params) {

    const recipeCombination = this.data.ingredientsList.filter(it => {
      return this.data.selectList.find(item => {
        return item.value === it.id
      }) !== undefined
    }).map(it => {
      return {
        ingredients: it,
        number: this.data.selectList.find(item => {
          return item.value === it.id
        })?.number
      }
    })

    if (this.validRecipeCombinationHasZero(recipeCombination)) {
      wx.showModal({
        showCancel: false,
        content: "份额不可以为0"
      })
      return
    }
    if (params === 'ANNOUNCED' && this.data.selectList.length < 1) {
      wx.showToast({
        title: '没有添加原料',
        icon: 'error'
      })
      return
    }
    const {
      name
    } = this.data;
    const numberSettings = this.selectComponent("#vc-number")?.getDataSource();
    const number_data = numberSettings.map(it => {
      return {
        name: it.name,
        numSelectManageId: it.numSelectManageId,
        remark: it.remark,
        sortNumber: it.sortNumber,
        value: it.value
      }
    })
    const data = {
      name,
      ...this.data._performanceData,
      recipeCombination,
      productionNumberDatas: number_data,
      status: params === 'ANNOUNCED' ? params : 'TO_BE_ANNOUNCED',
    }

    recipe.recipeAdd(data, (e) => {
      if (this.data.isGlaze) {
        this.setGlazeResult(e);
      }
      wx.showModal({
        title: '配方已创建',
        content: '是否返回上一页？',
        success(res) {
          if (res.confirm) {
            wx.navigateBack({
              delta: 1
            })
          }
        }
      })
    })
  },
  add() {
    this.addPF('ANNOUNCED');
  },
  onPerformanceInputChange(event){
    const {
      name,
      value 
    } = event.detail;
    const _performanceData = this.data._performanceData;
    _performanceData[name] = value;
    this.setData({
      _performanceData
    })
  },
  onLockOn(){
    this.setData({
      enabledScroll: false
    })
  },
  onUnLockOn(){
    this.setData({
      enabledScroll: true
    })
  },
  setGlazeResult(arg) {
    const pages = getCurrentPages();
    const beforePage = pages[pages.length - 2];
    beforePage?.addPFResult(arg);
  },
  onClose() {
    this.setData({
      show: false
    })
  },
  /**
   * @param {*} event 
   * @description 跳转到原料
   */
  toMaterial(event) {
    const id = event.currentTarget.dataset.value.value;
    wx.navigateTo({
      url: '../material/index?id=' + id,
    })
  },
  /**
   * @param {Array<T>} list 
   * @return Number
   */
  getTotal(list) {
    const total = list.reduce((preVal, currentVal) => {
      return preVal + Number(currentVal.number)
    }, 0).toFixed(2)
    return total;
  },
  onPickerShow() {
    this.setData({
      show: true
    })
  },
  onChange(event) {
    const data = event.detail;
    this.setData({
      checkboxValue: data
    })

  },
  onSelectConfirm() {
    this.onClose();
    const dropList = [...this.data.dropList];
    let selectList = [...this.data.selectList];
    let checkList = [...this.data.checkboxValue];
    const dl = dropList.filter(it => {
      return !checkList.includes(String(it.value))
    })
    const sl = [...selectList, ...dropList.filter(it => {
      return checkList.includes(String(it.value))
    }).map(it => {
      return {
        ...it,
        number: it.number || '0'
      }
    })]
    this.setData({
      dropList: dl,
      checkboxValue: [],
      selectList: sl
    })
  },
  showPicker() {
    //排序
    this.sortArray();
    this.onPickerShow();
  },
  sortArray() {
    const dropList = [...this.data.dropList];
    if (dropList.length < 1) return
    dropList.sort((a, b) => {
      return String(a.text)[0].localeCompare(String(b.text)[0], 'zh-CN', {
        numeric: true
      })
    })
    this.setData({
      dropList
    })
  },

  xyzChange(event) {
    const key = event.currentTarget.dataset.value;
    this.setData({
      [key]: event.detail
    })
  },
  setPage(id, glaze) {
    wx.setNavigationBarTitle({
      title: '新建配方'
    })

    this.setData({
      id,
      root: wx.getStorageSync('root'),
      isGlaze: Boolean(glaze)
    })

  },

  /**
   * 刷新配方列表
   */
  async onRefreshRecipe() {
    this.setData({
      refreshLoading: true
    })
    await this.fetchIngredientsList();
    const selectList = [...this.data.selectList],
      dropList = [...this.data.dropList],
      list = dropList.filter(it => {
        return selectList.find(item => {
          return item.value === it.value
        }) === undefined
      });
    this.setData({
      dropList: list,
      refreshLoading: false
    })

  },
  /**
   * 查询原料表
   */
  fetchIngredientsList() {
    return new Promise((resolve, reject) => {
      list({
        status: 'ANNOUNCED'
      }, (e) => {
        const alias = {},
          dropList = e.map(it => {
            alias[it.id] = it.name;
            return {
              text: it.name,
              value: it.id,
              number: ''
            }
          }).sort((a, b) => {
            return a.text.localeCompare(b.text)
          })
        this.setData({
          list: e,
          ingredientsList: e,
          alias,
          dropList
        })
        resolve();
      }, reject)
    })
  },
  selectHandler(event) {
    let arr = [...this.data.values];
    arr[event.currentTarget.dataset.index]['id'] = event.detail;
    this.setData({
      values: arr
    })
  },

  numberChange(event) {
    const id = event.currentTarget.dataset.id;
    const selectList = [...this.data.selectList];

    selectList.forEach(it => {
      if (it.value === id) {
        it.number = event.detail
      }
    })
    const total = this.getTotal(selectList);
    this.setData({
      selectList,
      total
    })
  },

  toggle(event) {
    const {
      index
    } = event.currentTarget.dataset;
    const checkbox = this.selectComponent(`.checkboxes-${index}`);
    checkbox.toggle();
  },
  noop() {},
  delectItem(event) {
    const index = event.currentTarget.dataset.index;
    const dropList = [...this.data.dropList],
      checkboxValue = [...this.data.checkboxValue],
      selectList = [...this.data.selectList];
    selectList[index].number = '0';
    checkboxValue.unshift(selectList[index].value);
    dropList.unshift(selectList[index]);
    selectList.splice(index, 1);
    const total = this.getTotal(selectList);
    this.setData({
      dropList,
      selectList,
      checkboxValue,
      total
    })
  },
  //判断资料里是否存在0
  validRecipeCombinationHasZero(arr) {
    return arr.some(it => {
      return it.number && String(it.number) == "0"
    })
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setPage(options.id, options.glaze);
    this.fetchIngredientsList();

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})